package tr.edu.ozyegin.ccrg.raid.network;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import tr.edu.ozyegin.ccrg.raid.master.Master;

public class Server extends Network {
	private ServerSocket serverSock = null;
	public Server(int port){
		super(port);
		this.port = port;
		while(!this.isConnected){
			try {
				this.serverSock = new ServerSocket(this.port);
				this.isConnected = true;
			} catch (IOException e) {
				this.port++;
				System.out.println("Socket is in use...\nPlease use another socket");
			}
		}
		
	}
	public int getPort(){
		return this.port;
	}
	public void Accept(Master r,int numberOfClients){
		if(this.isConnected){
			while(true){
				try {
					Socket sock = this.serverSock.accept();
					//sock.setKeepAlive(true);
					if(!r.isInQuorum(sock.getInetAddress().getHostAddress())){
						sock.close();
						continue;
					}
					Client client = new Client(sock);
					String clientType = (String) client.Read(String.class);
					if(clientType.equals("Master"))client.setClientType(ClientType.Master);
					else if(clientType.equals("Storage"))client.setClientType(ClientType.Storage);
					else if(clientType.equals("Parity"))client.setClientType(ClientType.Parity);
					System.out.println(clientType);
					r.addToList(client);
					if(numberOfClients != -1 && r.getListSize() == numberOfClients){
						r.brokeSequence();
						break;
					}
				} catch (IOException e) {
					System.out.println("Error occured while accepting connection...");
				}
			}
		}
	}
	public void Close(){
		try {
			this.serverSock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Socket is not closed");
		}
	}
	protected void finalize (){
		if(this.isConnected){
			try {
				this.serverSock.close();
			} catch (IOException e) {
				System.out.println("Cannot close server socket...");
			}
		}
	}
}
